<?php

namespace app\admin\model\mental;

use think\Model;


class Testson extends Model
{

    // 表名
    protected $name = 'mental_testson';
    protected $resultSetType = 'collection';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

    /**
     * Undocumented function
     * 保存数据
     * @return void
     */
    public function saveData($data, $main_id)
    {
        // var_dump($data);die;
        // $i = 1;
        //先清除老数据
        $this->where(['main_id' => $main_id])->delete();
        $new_data = [];
        foreach ($data as $key => $val) {
            $new_data[] = [
                'main_id' => $main_id,
                'question_id' => $val['id'],
                'component_id' => isset($val['component_id']) ? $val['component_id'] : 0,
                'skip' => isset($val['skip']) ? $val['skip'] : '',
                'option' => isset($val['option']) ? $val['option'] : '',
                'result' => isset($val['result']) ? $val['result'] : ''
            ];
            // var_dump($i++);
        }
        // var_dump($new_data);die;
        return $this->allowField(true)->saveAll($new_data);
    }

    public function setSkipAttr($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
    public function setOptionAttr($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
    public function setResultAttr($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
    public function getSkipAttr($value)
    {
        return json_decode($value, true);
    }
    public function getOptionAttr($value)
    {
        return json_decode($value, true);
    }
    public function getResultAttr($value)
    {
        return json_decode($value, true);
    }

    public function Question()
    {
        return $this->hasOne('Question', 'id', 'question_id')->bind(['title', 'id','question_text','dimensionKey']);
    }
}
